<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="数据状态" prop="isDel">
        <el-input
          v-model="queryParams.isDel"
          placeholder="请输入数据状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="门票名称" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入门票名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="stockDateStart">
        <el-date-picker clearable
          v-model="queryParams.stockDateStart"
          type="date"
          :picker-options="startPickerOptionsQuery"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="stockDateEnd">
        <el-date-picker clearable
          v-model="queryParams.stockDateEnd"
          type="date"
          :picker-options="endPickerOptionsQuery"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-hasPermi="['ticket:actstock:query']">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ticket:actstock:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ticket:actstock:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ticket:actstock:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ticket:actstock:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="门票名称" align="center" prop="activityName" />
      <el-table-column label="日期" align="center" prop="activityStockDate">
      </el-table-column>
      <el-table-column label="总库存" align="center" prop="activityStockCount" />
      <el-table-column label="剩余库存" align="center" prop="activityStockResidue" />
      <el-table-column label="已售卖" align="center" prop="activitySales" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ticket:actstock:edit']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ticket:stock:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改景区门票库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="dialogIsCloseOnModal" :close-on-press-escape="dialogIsCloseOnModal">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 景区信息 -->
        <el-divider content-position="left">景区信息</el-divider>
        <el-row>
          <el-col :span="24">
            <el-col :span="11">
              <el-form-item label="景区">
                  <el-select
                    v-model="form.ticOtherId"
                    placeholder="请选择景区"
                    clearable
                    style="width: 240px"
                    @change='changeScenicSelect'
                    disabled
                  >
                    <el-option
                      v-for="dict in dictScenicList"
                      :key="dict.ticOtherId"
                      :label="dict.name"
                      :value="dict.ticOtherId"
                    />
                  </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <!-- 选择景区后展示详细信息 -->
          <el-col :span="24" v-if='form.ticOtherId'>
            <el-col :span="11">
              <el-form-item label="星级" prop="starDetail">
                <el-input v-model="dictScenicListSelected.starDetail" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开放时间" >
                <el-input v-if="dictScenicListSelected.openTimeStart" :value="`${dictScenicListSelected.openTimeStart}-${dictScenicListSelected.openTimeEnd}`" disabled/>
                <el-input v-else value="" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="23">
              <el-form-item label="景点信息">
                <editor v-model="dictScenicListSelected.introduceDetails" :readOnly='false' :min-height="100"/>
              </el-form-item>
            </el-col>
            <el-col :span="23">
              <el-form-item label="游客须知">
                <editor v-model="dictScenicListSelected.touristNotice" :readOnly='false' :min-height="100"/>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="地理位置" >
                <el-input v-model="dictScenicListSelected.addressDetails" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="坐标点" prop="starDetail">
                <el-input v-if="dictScenicListSelected.latitude &&dictScenicListSelected.longitude" :value="`${dictScenicListSelected.latitude}-${dictScenicListSelected.longitude}`" disabled/>
                <el-input v-else value="" disabled/>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <!-- 门票信息 -->
        <el-divider content-position="left">门票信息</el-divider>
          <el-row>
            <el-col :span="24">
            <el-col :span="11">
              <el-form-item label="门票" prop="activityId">
                  <el-select
                    v-model="form.activityId"
                    placeholder="请选择门票"
                    clearable
                    style="width: 240px"
                    @change='changeStockSelect'
                    :disabled='!isEdit'
                  >
                    <el-option
                      v-for="dict in dictStockList"
                      :key="dict.activityId"
                      :label="dict.activityName"
                      :value="dict.activityId"
                    />
                  </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <!-- 选择门票后展示详细信息 -->
          <el-col :span="24" v-if='form.activityId'>
            <el-row>
          <!-- <el-col :span="11">
            <el-form-item label="门票名称" prop="activityName">
              <el-input disabled v-model="dictStockListSelected.activityName" placeholder="请输入门票名称" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="联系电话" prop="activityPhone">
              <el-input disabled v-model="dictStockListSelected.activityPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="有效时间">
              <el-date-picker
                disabled
                v-model="effectiveTime"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        <el-col :span="11">
            <el-form-item label="标签" prop="activityLabel">
              <el-input disabled v-model="dictStockListSelected.activityLabel" placeholder="请输入标签" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="限购数量" prop="limitPurchaseNum">
              <el-input-number disabled v-model="dictStockListSelected.limitPurchaseNum" placeholder="请输入限购数量" :min="0"  controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="数据状态" prop="scenicStatus">
                <el-select
                  v-model="dictStockListSelected.scenicStatus"
                  placeholder="数据状态"
                  clearable
                  disabled
                >
                  <el-option
                    v-for="dict in dict.type.ticket_scenic_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="认证方式" prop="scenicAuth">
              <el-select
                  v-model="dictStockListSelected.scenicAuth"
                  placeholder="认证方式"
                  clearable
                  disabled
                >
                  <el-option
                    v-for="dict in dict.type.sys_user_auth"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
            </el-form-item>
          </el-col>
            <el-col :span="24" v-if="isEdit">
              <el-form-item label="门票日期" prop="activityStockDateEnd">
              <el-date-picker
                v-model="form.activityStockDateStart"
                :picker-options="startPickerOptions"
                type="datetime"
                :editable="false"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择开始时间"
                />
                <span> - </span>
            <el-date-picker
                v-model="form.activityStockDateEnd"
                :picker-options="endPickerOptions"
                type="datetime"
                :editable="false"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择结束时间"
                />
              </el-form-item>
          </el-col>
          <el-col :span="11" v-else>
             <el-form-item label="门票日期">
                <el-input type="text" :value="scenicStockDate" disabled/>
              </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="库存" prop="activityStockCount">
              <el-input-number v-model="form.activityStockCount" placeholder="请输入库存" :min="0"  controls-position="right"/>
            </el-form-item>
          </el-col>
        </el-row>
          </el-col>
          </el-row>
        <el-divider content-position="left">票种信息</el-divider>
        <!-- 票种 -->
        <el-button type="primary" v-if="isEdit" icon="el-icon-plus" plain size="mini" @click="addTicketType">添加</el-button>
         <el-table
            :data="tableData"
          >
          <el-table-column prop="ticTypeId" label="票种" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.ticTypeId" placeholder="请选择票种" :disabled="!scope.row.isEdit || !isEdit" @change="changeSelect">
                  <el-option
                    v-for="dict in typeList"
                    :key="dict.ticTypeId"
                    :label="dict.typeName"
                    :value="dict.ticTypeId"
                    :disabled="dict.disabled"
                  />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="activityStockPrice" label="价格" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.activityStockPrice" :disabled="!scope.row.isEdit" placeholder="请输入价格"  :min="0" :precision="2" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
           <template slot-scope="scope">
             <el-button
              size="mini"
               v-if="scope.row.isEdit"
               type="text"
               icon="el-icon-check"
               v-hasPermi="['system:scenic:add']"
               @click="saveListItemRow(scope.row)"
             >保存
             </el-button>
             <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-else
              @click="editListItemRow(scope.row)"
              v-hasPermi="['system:scenic:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if='isEdit'
              @click="deleteListItemRow(scope.row)"
              v-hasPermi="['system:scenic:remove']"
            >删除</el-button>
           </template>
          </el-table-column>
         </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStock, getStock, delStock, addStock, updateStock ,getTypeList,getListScenic,getListTicOherBase} from "@/api/ticket/actstock";


import {  Message } from 'element-ui'
export default {
  name: "Stock",
  dicts: ["ticket_scenic_status", "sys_user_auth"],
  data() {
    return {
      // 编辑时门票日期
      scenicStockDate:[],
      // 新增/编辑日期时间范围
      effectiveTime: null,
      // 票种列表tabledata
      tableData:[],
      // 票种type
      typeList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 景区门票库存表格数据
      stockList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scenicId: null,
        scenicStockDate: null,
        stockDateEnd: null,
        stockDateStart: null,
        activityStockCount: null,
        scenicStockResidue: null,
        isDel: null,
        scenicName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityStockDateEnd:[
          { required: true, trigger: "blur", message: "请输入门票日期" },
        ],
        activityStockCount:[
          { required: true,message: "请输入库存",trigger: "blur" },
        ],
        activityId:[
          { required: true, message: "请选择门票",trigger: "change" },
        ]
      },
      // 景点下拉列表
      dictScenicList:[],
      // 选中景点
      dictScenicListSelected:'',
      // 判断是否编辑新增
      isEdit:false,
      // 门票下拉列表
      dictStockList:[],
      // 选中门票
      dictStockListSelected:'',
      startPickerOptions: {
        disabledDate: (time) => {
          let endTime = this.form.activityStockDateEnd
          if (endTime) {
            return time.getTime() > new Date(endTime).getTime()
          }
        }
      },
      endPickerOptions: {
        disabledDate: (time) => {
          let startTime = this.form.activityStockDateStart
          if (startTime) {
            return time.getTime() < new Date(startTime).getTime()
          }
        }
      },
      startPickerOptionsQuery: {
        disabledDate: (time) => {
          let endTime = this.queryParams.stockDateEnd
          if (endTime) {
            return time.getTime() > new Date(endTime).getTime()
          }
        }
      },
      endPickerOptionsQuery: {
        disabledDate: (time) => {
          let startTime = this.queryParams.stockDateStart
          if (startTime) {
            return time.getTime() < new Date(startTime).getTime()
          }
        }
      },
    };
  },
  created() {
    this.getList();
    this.getTypeListFun();
    this.getTicOherBase();
    this.getStockSelectList();
  },
  methods: {
    // 获取景点信息
    getTicOherBase(){
      getListTicOherBase().then(res=>{
        this.dictScenicList=res.data
      })
    },
    // 选择景点
    changeScenicSelect(selected){
      this.form.ticOtherId=selected
      this.dictScenicList.map(item=>{
        if(item.ticOtherId==selected){
          this.dictScenicListSelected=item
        }
      })
    },
    // 获取门票信息
    getStockSelectList(){
      getListScenic().then(res=>{
        this.dictStockList=res.data
      })
    },
    // 选择门票
    changeStockSelect(selected){
      console.log(this.dictStockList,selected)
      if(selected){
        this.dictStockList.map(item=>{
          if(item.activityId==selected){
            this.dictStockListSelected=item
            let temp=[]
            temp.push(item.activityTimeStart)
            temp.push(item.activityTimeEnd)
            this.effectiveTime=temp

            // 自动带出景点信息
            this.changeScenicSelect(item.ticOtherId)
          }
        })
      }else{
        this.changeScenicSelect('')
      }
    },
    // 获取票种下拉列表
    getTypeListFun(){
      getTypeList().then(res=>{
        this.typeList=res.data
      })
    },
    changeSelect(typeid){
      this.setDisable(typeid)
    },
    setDisable(typeid){
      this.typeList.forEach(item=> {
        if(item.ticTypeId==typeid){
          this.$set(item,'disabled',true)

        }
      })
    },
    // 票种添加行
    addTicketType(){
      this.tableData.push({
                  ticTypeId: '',
                  activityStockPrice: '',
                  ticScenicTypeId:new Date().getTime(),
                  isEdit: true
      })
    },
    // 票种保存当前行
    saveListItemRow(row){
      for (let key in row) {
        if (row[key] === '' || row[key] === null || typeof row[key] === 'undefined') {
           Message({ message: "请完善后保存", type: 'warning' })
           return
        }
      }
      this.$set(row,'isEdit',false)
      this.$forceUpdate()
      console.log(this.tableData)
    },
    // 票种编辑当前行
    editListItemRow(row){
      // row.isEdit=true
      this.$set(row,'isEdit',true)
      console.log(this.tableData)
    },
    deleteListItemRow(row){
      this.tableData=this.tableData.filter(item=>item.ticScenicTypeId!=row.ticScenicTypeId)
    },
    /** 查询景区门票库存列表 */
    getList() {
      this.loading = true;
      listStock(this.queryParams).then(response => {
        this.stockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        activityStockCount: null,
        activityStockDateEnd: null,
        activityStockDateStart: null,
        ticActivityTypeAddDTOList:[]
      };
      this.dictScenicListSelected=[]
      this.dictStockListSelected=[]
      this.tableData=[]
      this.getTypeListFun()
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.activityStockId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动门票库存";
      this.isEdit=true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const activityId = row.activityStockId || this.ids
      getStock(activityId).then(response => {
        this.form.activityStockCount = response.data.ticActivityStockVo.activityStockCount;
        this.scenicStockDate = response.data.ticActivityStockVo.activityStockDate;
        // 回显选中景区
        this.form.ticOtherId=response.data.ticActivityBusinessVo.ticOtherId
        // 回显选中门票
        this.form.activityId=response.data.ticActivityBusinessVo.activityId
        this.form.activityStockId=response.data.ticActivityStockVo.activityStockId;
        this.open = true;
        this.title = "修改活动门票库存";
        // 回显有效时间区间
        let temp=[]
        temp.push(response.data.ticActivityBusinessVo.activityTimeStart)
        temp.push(response.data.ticActivityBusinessVo.activityTimeEnd)
        this.effectiveTime=temp
        // 回显选中景区其他信息
        this.changeScenicSelect(response.data.ticActivityBusinessVo.ticOtherId)
        // 回显选中门票其他信息
        this.changeStockSelect(response.data.ticActivityBusinessVo.activityId)
        // 回显票种列表
        this.tableData=response.data.ticActivityTypeDetailVoList
        this.tableData.map(item=>{
          this.$set(item,'isEdit',true)
          // item.ticTypeId=String(item.ticTypeId)
        })
      });
      
      this.isEdit=false
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.tableData.length<=0){
              this.$modal.msgError("请添加票种信息后保存");
              return
          }
          // 拼票种List参数
          this.form.ticActivityTypeAddDTOList=this.tableData
          console.log(this.form)
          if (this.form.activityStockId != null) {
            updateStock(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStock(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scenicStockIds = row.activityId || this.ids;
      this.$modal.confirm('是否确认删除景区门票库存编号为"' + scenicStockIds + '"的数据项？').then(function() {
        return delStock(scenicStockIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ticket/stock/export', {
        ...this.queryParams
      }, `stock_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
